# Kill dotnet processes and free up ports 5000/5001
# Use this script when you get "address already in use" errors

Write-Host "=== WebRTC Port Cleanup Tool ===" -ForegroundColor Cyan
Write-Host "Checking for processes using ports 5000 and 5001..." -ForegroundColor Green

# Check which processes are using the ports
$portChecks = @(
    @{Port=5000; Name="HTTP"},
    @{Port=5001; Name="HTTPS"}
)

$processesToKill = @()

foreach ($check in $portChecks) {
    Write-Host "`nChecking port $($check.Port) ($($check.Name))..." -ForegroundColor Yellow
    
    $connections = netstat -ano | Select-String ":$($check.Port)\s" | Where-Object { $_ -match "LISTENING" }
    
    if ($connections) {
        foreach ($conn in $connections) {
            if ($conn -match "(\d+)$") {
                $pid = $matches[1]
                try {
                    $process = Get-Process -Id $pid -ErrorAction Stop
                    Write-Host "  ✓ Found process: $($process.ProcessName) (PID: $pid)" -ForegroundColor Red
                    $processesToKill += @{PID=$pid; Name=$process.ProcessName; Port=$check.Port}
                }
                catch {
                    Write-Host "  ✗ Process with PID $pid not found" -ForegroundColor Gray
                }
            }
        }
    }
    else {
        Write-Host "  ✓ Port $($check.Port) is free" -ForegroundColor Green
    }
}

if ($processesToKill.Count -eq 0) {
    Write-Host "`n🎉 All ports are free! No cleanup needed." -ForegroundColor Green
    Write-Host "You can now run: dotnet run" -ForegroundColor Cyan
    exit 0
}

Write-Host "`n⚠️  Found $($processesToKill.Count) processes using WebRTC ports:" -ForegroundColor Yellow
foreach ($proc in $processesToKill) {
    Write-Host "   • $($proc.Name) (PID: $($proc.PID)) on port $($proc.Port)" -ForegroundColor White
}

# Ask for confirmation
Write-Host "`n❓ Do you want to kill these processes? [Y/N]" -ForegroundColor Cyan -NoNewline
$response = Read-Host " "

if ($response -match "^[Yy]") {
    Write-Host "`nKilling processes..." -ForegroundColor Yellow
    
    foreach ($proc in $processesToKill) {
        try {
            Stop-Process -Id $proc.PID -Force
            Write-Host "  ✓ Killed $($proc.Name) (PID: $($proc.PID))" -ForegroundColor Green
        }
        catch {
            Write-Host "  ✗ Failed to kill $($proc.Name) (PID: $($proc.PID)): $($_.Exception.Message)" -ForegroundColor Red
        }
    }
    
    # Wait a moment for ports to be released
    Start-Sleep -Seconds 2
    
    # Verify ports are now free
    Write-Host "`nVerifying ports are free..." -ForegroundColor Yellow
    $stillBusy = @()
    
    foreach ($check in $portChecks) {
        $connections = netstat -ano | Select-String ":$($check.Port)\s" | Where-Object { $_ -match "LISTENING" }
        if ($connections) {
            $stillBusy += $check.Port
            Write-Host "  ✗ Port $($check.Port) still in use" -ForegroundColor Red
        }
        else {
            Write-Host "  ✓ Port $($check.Port) is now free" -ForegroundColor Green
        }
    }
    
    if ($stillBusy.Count -eq 0) {
        Write-Host "`n🎉 All ports are now free!" -ForegroundColor Green
        Write-Host "🚀 You can now run: dotnet run" -ForegroundColor Cyan
    }
    else {
        Write-Host "`n⚠️  Some ports are still busy: $($stillBusy -join ', ')" -ForegroundColor Yellow
        Write-Host "💡 You may need to:" -ForegroundColor Cyan
        Write-Host "   1. Restart your computer" -ForegroundColor White
        Write-Host "   2. Use different ports in appsettings.json" -ForegroundColor White
        Write-Host "   3. Check for other applications using these ports" -ForegroundColor White
    }
}
else {
    Write-Host "`n❌ Operation cancelled by user." -ForegroundColor Red
    Write-Host "💡 Alternative solutions:" -ForegroundColor Yellow
    Write-Host "   1. Change ports in appsettings.json" -ForegroundColor White
    Write-Host "   2. Restart your computer" -ForegroundColor White
    Write-Host "   3. Use Docker: docker-compose up" -ForegroundColor White
}

Write-Host "`n📝 Common causes of port conflicts:" -ForegroundColor Cyan
Write-Host "   • Previous dotnet run session not properly terminated" -ForegroundColor White
Write-Host "   • Visual Studio debugging session still running" -ForegroundColor White
Write-Host "   • IIS Express using the same ports" -ForegroundColor White
Write-Host "   • Other web applications running on same ports" -ForegroundColor White 